package com.bigwolf.gateway.service.impl;

import com.bigwolf.common.core.constant.CacheConstants;
import com.bigwolf.common.core.constant.Constants;
import com.bigwolf.common.core.exception.user.CaptchaException;
import com.bigwolf.common.core.utils.AjaxResult;
import com.bigwolf.common.core.utils.StringUtils;
import com.bigwolf.common.redis.service.RedisCache;
import com.bigwolf.gateway.service.ValidateCodeService;
import com.wf.captcha.SpecCaptcha;
import org.aspectj.weaver.AjAttribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {
    /**
     * 验证码宽度
     */
    Integer CAPTCHA_WIDTH = 130;
    /**
     * 验证码高度
     */
    Integer CAPTCHA_HEIGHT = 48;

    /**
     * 验证码长度
     */
    Integer CAPTCHA_LENGTH = 4;

    @Autowired
    private RedisCache redisCache;

    public AjaxResult createCaptcha() {
        String uuid = UUID.randomUUID().toString();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        Map<String, String> captchaMap = new HashMap<>();

        SpecCaptcha specCaptcha = new SpecCaptcha(CAPTCHA_WIDTH,CAPTCHA_HEIGHT,CAPTCHA_LENGTH);
        String codeValue = specCaptcha.text().toLowerCase();
        specCaptcha.out(os);

        redisCache.setCacheObject(verifyKey, codeValue, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.getEncoder().encodeToString(os.toByteArray()));
        return ajax;
    }

    @Override
    public void checkCaptcha(String code, String uuid) throws CaptchaException {
        if (StringUtils.isEmpty(code))
        {
            throw new CaptchaException("验证码不能为空");
        }
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        if (captcha == null)
        {
            System.out.println("验证码已失效");
            throw new CaptchaException("验证码已失效");
        }
        redisCache.deleteObject(verifyKey);
        if (!code.equalsIgnoreCase(captcha))
        {
            System.out.println("验证码已失效");
            throw new CaptchaException("验证码错误");
        }
    }
}

